package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.service.UserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Date;

/**
 * 用户服务实现
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    public UserServiceImpl(UserMapper userMapper, @Lazy PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User create(User user) {
        // 设置默认密码
        if (user.getPassword() == null) {
            user.setPassword(passwordEncoder.encode("123456"));
        } else {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        
        // 设置创建时间
        user.setCreateTime(new Date());
        
        // 使用MyBatis Plus的save方法
        save(user);
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("Loading user by username: {}", username);
        User user = userMapper.findByUsername(username);
        
        if (user == null) {
            log.error("User not found: {}", username);
            
            // 如果是微信登录生成的用户名（以wx_开头），可以尝试创建用户
            if (username.startsWith("wx_")) {
                log.info("Attempting to create WeChat user: {}", username);
                String openid = username.substring(3); // 去掉"wx_"前缀，获取openid
                
                User newUser = new User();
                newUser.setUsername(username);
                newUser.setNickName("微信用户");
                newUser.setEnabled(true);
                newUser.setOpenid(openid); // 设置openid
                newUser = create(newUser);
                
                log.info("Created new WeChat user: {}, openid: {}", newUser.getUsername(), newUser.getOpenid());
                
                return new JwtUserDto(
                        newUser.getId(),
                        newUser.getUsername(),
                        newUser.getPassword(),
                        newUser.getEnabled(),
                        Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")),
                        newUser.getCreateTime()
                );
            }
            
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        log.info("User found: {}", user.getUsername());
        
        return new JwtUserDto(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getEnabled(),
                Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")),
                user.getCreateTime()
        );
    }
} 